package com.example.demo.controller;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.demo.config.PropertiesConfig;
import com.example.demo.entity.TemplateBody;
import com.example.demo.entity.TemplateBodyData;
import com.example.demo.service.AccessTokenService;
import com.google.gson.Gson;

@RestController
public class MessageController {
	
	protected final Logger logger= LoggerFactory.getLogger(getClass());

	@Autowired
	private PropertiesConfig propertiesConfig;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private AccessTokenService accessTokenService;
	
	@PostMapping("/template/sendCustom")
	public Object templateSendCustom(@RequestBody Map<String,Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 20000);
		resultMap.put("message", "操作成功");
		try {
			// 模板消息接口url、accessToken、templateId
			String accessToken = accessTokenService.findById(propertiesConfig.getAppId()).get().getAccessToken();
			String tempUrlTemplateSend = propertiesConfig.getUrlTemplateSend();
			String urlTemplateSend = MessageFormat.format(tempUrlTemplateSend, accessToken);
			// 构建表单参数
			String jsonTemplateBody = new Gson().toJson(paramsMap);
			// 调用微信远程接口
			Map apiResult = new HashMap<String, Object>();
			try {
				logger.info("参数:\n\t{}",jsonTemplateBody);
				apiResult = restTemplate.postForObject(urlTemplateSend, jsonTemplateBody, Map.class);
				logger.info("模板消息结果：\n\t{}", apiResult);
			} catch (Exception e) {
				throw new Exception("微信远程接口调用异常，url="+tempUrlTemplateSend);
			}
			int errcode = (int)apiResult.get("errcode");
			if(errcode != 0) {
				resultMap.put("code", errcode);
				throw new Exception("微信远程接口返回值异常，apiResult="+apiResult);
			}
			
		} catch (Exception e) {
			resultMap.put("message", "操作失败，"+e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 微信模板消息接口
	 * @param first
	 * @param touser
	 * @param keyword1
	 * @param keyword2
	 * @param keyword3
	 * @param keyword4
	 * @param keyword5
	 * @return
	 */
	@PostMapping("/template/send")
	public Object templateSend(@RequestBody Map<String,Object> paramsMap) {
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 20000);
		resultMap.put("message", "操作成功");
		//接收的参数
		String templateId = (String)paramsMap.get("templateId");
		String urlTemplate = (String)paramsMap.get("url");
		String first = (String)paramsMap.get("first");
		String touser = (String)paramsMap.get("touser");
		String keyword1 = (String)paramsMap.get("keyword1");
		String keyword2 = (String)paramsMap.get("keyword2");
		String keyword3 = (String)paramsMap.get("keyword3");
		String keyword4 = (String)paramsMap.get("keyword4");
		String keyword5 = (String)paramsMap.get("keyword5");
		String remark = (String)paramsMap.get("remark");
		if(StringUtils.isEmpty(templateId)) {
			templateId = "S7g_TPT5pD2sy2HCP_JvrLgL6glSrXKTLiVhE4yYnl0";
		}
		if(StringUtils.isEmpty(urlTemplate)) {
			urlTemplate = "10.101.1.120/sectotal";
		}
		if(StringUtils.isEmpty(first)) {
			first = "Sectotal安全扫描结果提醒";
		}
		if(StringUtils.isEmpty(touser)) {
			touser = "oJUHLwGuVtX0Srv9_YyP0c3uDIKY";
		}
		if(StringUtils.isEmpty(keyword1)) {
			keyword1 = "长城网际";
		}
		if(StringUtils.isEmpty(keyword2)) {
			keyword2 = "内容监测系统";
		}
		if(StringUtils.isEmpty(keyword3)) {
			keyword3 = "10.101.1.120/sectotal";
		}
		if(StringUtils.isEmpty(keyword4)) {
			keyword4 = "Sectotal内置监测规则";
		}
		if(StringUtils.isEmpty(keyword5)) {
			keyword5 = "SQL注入10个；违规图片1张，违规正文3个";
		}
		if(StringUtils.isEmpty(remark)) {
			remark = "请注意防护，谢谢。";
		}
		// 模板消息接口url、accessToken、templateId
		String accessToken = accessTokenService.findById(propertiesConfig.getAppId()).get().getAccessToken();
		String tempUrlTemplateSend = propertiesConfig.getUrlTemplateSend();
		String urlTemplateSend = MessageFormat.format(tempUrlTemplateSend, accessToken);
		// 构建表单参数
		Map<String, TemplateBodyData> data = new HashMap<String, TemplateBodyData>();
		data.put("first", new TemplateBodyData(first, "#173177"));
		data.put("keyword1", new TemplateBodyData(keyword1, "#173177"));
		data.put("keyword2", new TemplateBodyData(keyword2, "#173177"));
		data.put("keyword3", new TemplateBodyData(keyword3, "#173177"));
		data.put("keyword4", new TemplateBodyData(keyword4, "#173177"));
		data.put("keyword5", new TemplateBodyData(keyword5, "#173177"));
		data.put("remark", new TemplateBodyData(remark, "#173177"));
		TemplateBody templateBody = new TemplateBody();
		templateBody.setTemplate_id(templateId);
		templateBody.setTouser(touser);
		templateBody.setUrl(urlTemplate);
		templateBody.setData(data);
		String jsonTemplateBody = new Gson().toJson(templateBody);
		System.out.println(jsonTemplateBody);
		// 调用模板消息接口
		try {
			Map apiResult = restTemplate.postForObject(urlTemplateSend, jsonTemplateBody, Map.class);
			System.out.println("模板消息结果：\n" + apiResult);
		} catch (Exception e) {
			resultMap.put("message", "操作失败，"+e.getMessage());
		}
		return resultMap;

//		调用成功
//		 {
//		    "errcode": 0,
//		    "errmsg": "ok",
//		    "msgid": 1406296396546015233
//		 } 
//		 调用失败
//		 {errcode=44002, errmsg=empty post data hint: [u0891d450]}

//		request body 参数
//		{
//		   "touser":"oJUHLwGuVtX0Srv9_YyP0c3uDIKY",
//		   "template_id":"cqUTvyrcUsbT_4V_ooyT9cMr3Uf0oxa_2m3E7ST1LQg",
//		   "url":"https://www.baidu.com/",
//		   "data":{
//		           "first": {
//		               "value":"Sectotal安全扫描结果提醒",
//		               "color":"#173177"
//		           },
//		           "keyword1":{
//		               "value":"长城网际",
//		               "color":"#173177"
//		           },
//		           "keyword2": {
//		               "value":"内容监测系统",
//		               "color":"#173177"
//		           },
//		           "keyword3": {
//		               "value":"http://host1a8af2f56.w187.171kj.cn",
//		               "color":"#173177"
//		           },
//		           "keyword4": {
//		               "value":"Sectotal配置监测规则",
//		               "color":"#173177"
//		           },
//		           "keyword5": {
//		               "value":"SQL注入10个；违规图片1张，违规正文3个",
//		               "color":"#173177"
//		           },
//		           "remark":{
//		               "value":"欢迎再次使用！",
//		               "color":"#173177"
//		           }
//		   }
//		}
	}
}
